import JsRsaSign from "jsrsasign";
import CryptoJS from 'crypto-js';

/**
 * SHA256和RSA加签
 * @param privateKey 私钥
 * @param msg 加签内容
 * @returns {string} Base64编码签名内容
 */
export function signBySHA256WithRSA(privateKey, msg) {
  const key = JsRsaSign.KEYUTIL.getKey(privateKey);
  const signature = new JsRsaSign.KJUR.crypto.Signature({
    alg: "SHA256withRSA",
  });
  signature.init(key);
  signature.updateString(msg);
  // 签名后的为16进制字符串，这里转换为16进制字符串
  return JsRsaSign.hextob64(signature.sign());
}

/**
 * AES加密
 * @param key
 * @param plainText 明文
 * @returns {string} Base64编码的密文
 */
export function encryptByAES(plainText) {
  // 先hex解密密钥
  const key = import.meta.env.VITE_AES_ENCRYPTION_KEY;
  const keyBytes = CryptoJS.enc.Hex.parse(key);
  // 判断plainText是不是json字符串
  if(typeof plainText === 'string') {
    try {
      JSON.parse(plainText);
      const encrypted = CryptoJS.AES.encrypt(plainText, keyBytes, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
      });
      return {
        encrypt: encrypted.toString()
      }
    } catch (e) {
      console.error(e);
    }
  } else {
    // plainText 转换为 string
    plainText = plainText.toString();
    const encrypted = CryptoJS.AES.encrypt(plainText, keyBytes, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return {
        encrypt: encrypted.toString()
    }
  }
}

/**
 * AES解密
 * @param key
 * @param cipherText
 * @returns {string} 明文
 */
export function decryptByAES(cipherText) {
  // console.log("cipherText: " + cipherText);
  // 先hex解析密钥
  const keyBytes = CryptoJS.enc.Hex.parse(import.meta.env.VITE_AES_ENCRYPTION_KEY);
  // 直接使用密文字符串，CryptoJS会自动处理Base64解码
  const decrypted = CryptoJS.AES.decrypt(cipherText, keyBytes, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  const decryptedStr = decrypted.toString(CryptoJS.enc.Utf8);
  try {
    const decryptedStrJson = JSON.parse(decryptedStr);
    return decryptedStrJson;
  } catch (e) {
    return decryptedStr;
  }
}

